﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Jinjia.Approve.Entity;
using Jinjia.Approve.Entity.Entity;
using Jinjia.Approve.IRepository;
using Jinjia.Approve.Model.VM;
using Jinjia.Core.BaseInfrastructure.StorageModel;
using Jinjia.Core.BaseInfrastructure.StorageModel.Impl;
using Jinjia.Core.UnitOfWork.UnitOfWorkComponent;
using SqlSugar;

namespace Jinjia.Approve.Repository
{
    public class ErpaViewedLogRepository : BaseRepository<erpa_viewed_log_tbl>, IErpaViewedLogRepository
    {
        public ErpaViewedLogRepository(IUnitOfWork unitOfWork, IInitUserInfo initUserInfo, string ConnId = "") : base(unitOfWork, initUserInfo, ConnId)
        {
        }

        public async Task<List<ErpaViewedLogViewModel>> GetViewLogByModularKeyAndBId(string doc_model, string biz_order_id)
        {
            var list = await _db.Queryable<erpa_viewed_log_tbl, erpa_user_tbl>((a, b) =>
                    new JoinQueryInfos(JoinType.Left, a.create_user_id == b.id))
                .Where(a => a.doc_model == doc_model && a.biz_order_id == biz_order_id && a.deleted == 0)
                .OrderBy(" a.create_time asc")
                .Select<ErpaViewedLogViewModel>("a.id,a.total,b.user_name,a.update_time")
                .ToListAsync();
            return list;
        }

        public async Task<erpa_viewed_log_tbl> GetViewLogByModularKeyAndBIdAndUserId(string doc_model, string biz_order_id, int user_id)
        {
            var tbl = await _db.Queryable<erpa_viewed_log_tbl>()
                .FirstAsync(a => a.doc_model == doc_model &&
                                 a.biz_order_id == biz_order_id &&
                                 a.deleted == 0 &&
                                 a.create_user_id == user_id);
            return tbl;
        }

        public async Task<int> Save(erpa_viewed_log_tbl data)
        {
            if (data.id <= 0) //新增
            {
                var id = await InsertAsync(data);
                return data.id;
            }
            else
            {
                await UpdateAsync(data);
                return data.id;
            }
        }
    }
}